/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.sun.courier.view;

import com.sun.courier.dal.CourierDAL;
import com.sun.courier.dal.CourierManageDAL;
import com.sun.courier.dal.DepartmentDAL;
import com.sun.courier.dal.EmployeeDAL;
import com.sun.courier.dto.Employee_EmpLoginDTO;
import com.sun.courier.entity.CourierManage;
import com.sun.courier.entity.Department;
import com.sun.courier.utilities.Utilities;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author HONG QUAN
 */
public class SendToDestinationStoreActions extends JDialog implements ActionListener{
    CourierManageDAL cmDal = new CourierManageDAL();
    CourierDAL cDal = new CourierDAL();

    JPanel pnMain = new JPanel();
    JPanel pnTitle = new JPanel();
    JPanel pnCenter = new JPanel();
    JPanel pnButton = new JPanel();

    JLabel lblTitle = new JLabel("Send Courier To Store");

    JLabel lblCourierId = new JLabel("Courier Id");
    JLabel lblSenderName = new JLabel("Sender Name");// Ten nhan vien nhan hang cua khach hang: lay tu dang nhap.
    JLabel lblReceiverName = new JLabel("Receiver Name");
    JLabel lblUpdateTime = new JLabel("Send Time");//Cai nay phai an
    JLabel lblDescription = new JLabel("Description");
    JLabel lblEmployeeId = new JLabel("EmployeeId");
    JLabel lblMess = new JLabel();

    JTextField txtCourierId = new JTextField();
    JTextField txtSenderName = new JTextField();
    JTextField txtReceiverName = new JTextField();
    JTextField txtUpdateTime = new JTextField();
    JTextArea txtDescription = new JTextArea();
    JTextField txtEmployeeId = new JTextField();

    JButton btnSend = new JButton("Send");
    JButton btnReset = new JButton("Reset");

    DefaultTableModel model = null;
    ArrayList lst;
    String empId = Utilities.empId;

    private int ind = -1;
    ListSelectionModel listSelectionModel;
    private JTable table;

    public SendToDestinationStoreActions(DefaultTableModel model, ArrayList lst) {
        registerListners();
        this.model = model;
        this.lst = lst;
        setValuesToTextbox();
    }
    
    protected void setValuesToTextbox() {
        createControlPanel();
        txtEmployeeId.setText(empId);//Tam thoi fix cung de login thi chinh sau: cua nguoi gui
        txtSenderName.setText(cDal.getEmployeeName(Integer.parseInt(empId)));//Tam thoi set cung nhu vay de login chinh lai
    }
    
    public void createControlPanel() {
        pnTitle.setLayout(new FlowLayout());
        pnTitle.setBorder(BorderFactory.createEtchedBorder());
        lblTitle.setFont(new Font("Arial", Font.BOLD, 25));
        pnTitle.add(lblTitle);

        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        pnCenter.setBorder(BorderFactory.createEtchedBorder());
        pnCenter.setLayout(gridbag);

        c.gridx = 0;
        c.gridy = 0;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 3, 3);
        lblCourierId.setVisible(false);
        c.anchor = GridBagConstraints.SOUTHWEST;
        pnCenter.add(lblCourierId, c);

        c.gridx = 1;
        c.gridy = 0;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 0, 3);
        c.anchor = GridBagConstraints.SOUTHWEST;
        txtCourierId.setVisible(false);
        txtCourierId.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtCourierId, c);

        c.gridx = 0;
        c.gridy = 1;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 3, 3);
        c.anchor = GridBagConstraints.SOUTHWEST;
        pnCenter.add(lblSenderName, c);
        c.gridx = 1;
        c.gridy = 1;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 0, 3);
        c.anchor = GridBagConstraints.SOUTHWEST;
        txtSenderName.setEditable(false);
        txtSenderName.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtSenderName, c);

        c.gridx = 0;
        c.gridy = 2;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 3, 3);
        c.anchor = GridBagConstraints.SOUTHWEST;
        pnCenter.add(lblReceiverName, c);
        c.gridx = 1;
        c.gridy = 2;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 0, 3);
        c.anchor = GridBagConstraints.SOUTHWEST;
        txtReceiverName.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtReceiverName, c);
        txtReceiverName.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                SendToDestinationStoreActions.PassReceiverActions par = new SendToDestinationStoreActions.PassReceiverActions();
                par.setBackground(Color.GRAY);
                par.setModal(true);
                par.setAlwaysOnTop(true);
                par.setSize(new Dimension(650, 350));
                par.setVisible(true);
            }
        });
        c.gridx = 1;
        c.gridy = 2;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 3, 3);
        c.anchor = GridBagConstraints.SOUTHWEST;
        pnCenter.add(lblMess, c);

        c.gridx = 0;
        c.gridy = 3;
        c.anchor = GridBagConstraints.BELOW_BASELINE_LEADING;
        pnCenter.add(lblDescription, c);
        c.gridx = 1;
        c.gridy = 3;
        txtDescription.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        txtDescription.setPreferredSize(new Dimension(300, 120));
        pnCenter.add(txtDescription, c);

        c.gridx = 0;
        c.gridy = 4;
        lblUpdateTime.setVisible(false);
        pnCenter.add(lblUpdateTime, c);
        c.gridx = 1;
        c.gridy = 4;
        txtUpdateTime.setVisible(false);
        txtUpdateTime.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtUpdateTime, c);

        c.gridx = 0;
        c.gridy = 5;
        lblEmployeeId.setVisible(false);
        pnCenter.add(lblEmployeeId, c);
        c.gridx = 1;
        c.gridy = 5;
        txtEmployeeId.setVisible(false);
        txtEmployeeId.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtEmployeeId, c);

        pnButton.setLayout(new FlowLayout());
        pnButton.setBorder(BorderFactory.createEtchedBorder());
        pnButton.add(btnSend);
        lblTitle.setText("Send Courier To Store");

        pnButton.add(btnReset);

        pnMain.setLayout(new BorderLayout());
        pnMain.setBackground(Color.LIGHT_GRAY);
        pnMain.setBorder(BorderFactory.createRaisedSoftBevelBorder());
        pnMain.add(pnTitle, BorderLayout.NORTH);
        pnMain.add(pnCenter, BorderLayout.CENTER);
        pnMain.add(pnButton, BorderLayout.SOUTH);

        getContentPane().add(pnMain, BorderLayout.CENTER);
    }
    
    public void registerListners() {
        btnSend.addActionListener(this);
        btnReset.addActionListener(this);
    }
    
    protected void sendCourierToDestinationStore() {
        if (txtDescription.getText().isEmpty() || txtReceiverName.getText().isEmpty()|| txtDescription.getText().isEmpty() || txtReceiverName.getText().isEmpty()) {
            JOptionPane.showMessageDialog(pnCenter, "You can not left blank any textboxes!", "Result", JOptionPane.INFORMATION_MESSAGE);
            return;
        } else {
            Boolean kq = false;
            int r = 0;
            CourierManage cm = new CourierManage();
            cm.setSender(Integer.parseInt(txtEmployeeId.getText()));
            cm.setDescription(txtDescription.getText());
            Date dNow = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("MM/dd/yyyy");
            cm.setUpdatetime(ft.format(dNow));
            int employeeId = cDal.getEmployeeIdByUsername(txtReceiverName.getText().trim());
            if (employeeId > 1) {
                cm.setReceiver(employeeId);
                int row = lst.size();
                int mdrow = model.getRowCount();
                for (int i = 0; i < row; i++) {
                    cm.setCourierId(Integer.parseInt(lst.get(i).toString()));
                    int position = cmDal.getPositionOfDespatchingCourier(cm);
                    if (position > 0) {
                        kq = cmDal.SendToDestinationStore(cm);
                        for (int j = 0; j < mdrow; j++) {
                            if (lst.get(i) == model.getValueAt(j, 0)) {
                                if (kq) {
                                    r = 1;
                                    model.removeRow(j);
//                                    model.setValueAt("Sending", j, 5);
//                                    model.fireTableDataChanged();
                                } else {
                                    r = 0;
                                }
                            }
                        }
                    } else {
                        r = 2;
                    }
                }
            } else {
                lblMess.setText("Username incorrect!");
                txtReceiverName.setText("");
                return;
            }
            if (r == 1) {
                JOptionPane.showMessageDialog(pnCenter, "Courier Is Sending!", "Result", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            }
            if (r == 2) {
                JOptionPane.showMessageDialog(pnCenter, "There are some values already sent!", "Result", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            }
        }
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(btnSend)) {
            sendCourierToDestinationStore();
        } else if (e.getSource().equals(btnReset)) {
            txtReceiverName.setText("");
            txtDescription.setText("");
        }
    }
    
    //Inner choose receiver class
    private class PassReceiverActions extends JDialog implements ActionListener {

        JLabel lblTitle = new JLabel("Choose A Person");

        JPanel pnMainInner = new JPanel();
        JPanel pnTitleInner = new JPanel();
        JPanel pnCenterInner = new JPanel();
        JPanel pnButtomInner = new JPanel();
        JComboBox cbStore;
        Vector modelStore;
//        JTable table;
        JButton btnAdd = new JButton("Add");

        GridBagLayout gridbagInner = new GridBagLayout();
        GridBagConstraints cInner = new GridBagConstraints();
        ArrayList<Department> lstStore = new ArrayList<>();
        ArrayList<Employee_EmpLoginDTO> lstDto = new ArrayList<>();
        DepartmentDAL dDal = new DepartmentDAL();
        EmployeeDAL eDal = new EmployeeDAL();
        String[] columnNames = {"Employee Name", "User Name", "Address", "Phone"};
        String[][] tableData = new String[1][4];
        ListSelectionModel listSelectionModel;
        JScrollPane tablePane;
        private TablePanel gregsPanel = new TablePanel("", tableData, columnNames);

        public PassReceiverActions() {

            lstStore = dDal.showAllStore();
            lstDto = eDal.getAllStoreEmployee();
            createStoreControl();
            registerActionListener();
        }

        private void createStoreControl() {
            modelStore = showAllStoreCombo();
            pnTitleInner.setLayout(new FlowLayout());
            pnTitleInner.add(lblTitle);
            
            cbStore = new JComboBox(modelStore);
            cbStore.setPreferredSize(new Dimension(300, 30));
            pnCenterInner.add(cbStore, BorderLayout.PAGE_START);
            pnCenterInner.add(gregsPanel.getMainPanel(), BorderLayout.CENTER);
            setLayout(new BorderLayout());
            pnButtomInner.add(btnAdd);
            
            pnMainInner.setLayout(new BorderLayout());
            pnMainInner.setBackground(Color.LIGHT_GRAY);
            pnMainInner.add(pnTitleInner, BorderLayout.NORTH);
            pnMainInner.add(pnCenterInner, BorderLayout.CENTER);
            pnMainInner.add(pnButtomInner, BorderLayout.SOUTH);
            getContentPane().add(pnMainInner, BorderLayout.CENTER);
        }

        private Vector showAllStoreCombo() {
            Vector modelct = new Vector();
            modelct.add(0, "Choose An Employee");
            for (int i = 0; i < lstStore.size(); i++) {
                modelct.addElement(new SendToDestinationStoreActions.Item(lstStore.get(i).getDepId(), lstStore.get(i).getDepartmentName().toString()));
            }
            return modelct;
        }

        private void registerActionListener() {
            cbStore.addActionListener(this);
            btnAdd.addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String[][] newdata = new String[lstDto.size()][4];
            SendToDestinationStoreActions.Item item = (SendToDestinationStoreActions.Item) cbStore.getSelectedItem();
            int depId = item.getId();
            if (e.getSource().equals(cbStore)) {
                int j = 0;
                for (int i = 0; i < lstDto.size(); i++) {
                    if (lstDto.get(i).getE().getDepId() == depId) {
                        newdata[j][0] = lstDto.get(i).getE().getEmployeeName();
                        newdata[j][1] = lstDto.get(i).getL().getUsername();
                        newdata[j][2] = lstDto.get(i).getE().getAddress();
                        newdata[j][3] = lstDto.get(i).getE().getPhone();
                        j = j + 1;
                    }
                }
                gregsPanel.setTableModelDataVector(newdata, columnNames);
                gregsPanel.fireTableDataChanged();
            } else if (e.getSource().equals(btnAdd)) {
                txtReceiverName.setText(table.getValueAt(ind, 1).toString());
                this.dispose();
            }
        }

    }
    //INNER IN INNER CLASS
    class TablePanel {

        private JPanel mainPanel = new JPanel();
        private DefaultTableModel dm;
        private JScrollPane scrollpane;

        public TablePanel(String title, Object[][] data, Object[] columnNames) {
            table = new JTable();
            dm = new DefaultTableModel(data, columnNames);
            table.setModel(dm);
            listSelectionModel = table.getSelectionModel();
            listSelectionModel.addListSelectionListener(new SendToDestinationStoreActions.SharedListSelectionHandler());
            table.setSelectionModel(listSelectionModel);
            table.setRowHeight(30);
            scrollpane = new JScrollPane(table);
            mainPanel.setBorder(BorderFactory.createTitledBorder(title));
            mainPanel.setLayout(new BorderLayout(1, 1));
            mainPanel.setPreferredSize(new Dimension(600, 200));
            mainPanel.add(scrollpane, BorderLayout.CENTER);
        }

        public void setTableModelDataVector(Object[][] data, Object[] columnNames) {
            dm.setDataVector(data, columnNames);
        }

        public void fireTableDataChanged() {
            dm.fireTableDataChanged();
        }

        public JScrollPane getScrollPane() {
            return scrollpane;
        }

        public JComponent getMainPanel() {
            return mainPanel;
        }
    }

    class ItemRenderer extends BasicComboBoxRenderer {

        public Component getListCellRendererComponent(
                JList list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index,
                    isSelected, cellHasFocus);

            if (value != null) {
                Item item = (Item) value;
                setText(item.getDescription().toUpperCase());
            }

            if (index == -1) {
                Item item = (Item) value;
                setText("" + item.getId());
            }

            return this;
        }
    }

    class Item {

        private int id;
        private String description;

        public Item(int id, String description) {
            this.id = id;
            this.description = description;
        }

        public int getId() {
            return id;
        }

        public String getDescription() {
            return description;
        }

        public String toString() {
            return description;
        }
    }

    class SharedListSelectionHandler implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();

            int firstIndex = e.getFirstIndex();
            int lastIndex = e.getLastIndex();
            boolean isAdjusting = e.getValueIsAdjusting();
            if (lsm.isSelectionEmpty()) {

            } else {
                // Find out which indexes are selected.
                int minIndex = lsm.getMinSelectionIndex();
                int maxIndex = lsm.getMaxSelectionIndex();
                for (int i = minIndex; i <= maxIndex; i++) {
                    if (lsm.isSelectedIndex(i)) {
                        ind = i;
                    }
                }
            }
        }
    }
}
